/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-02-21
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-04-16
 * @Description: 
 */
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:image_picker/image_picker.dart';

// 路由
import 'package:chat_client/router/router.dart';
// 服务
import 'package:chat_client/services/login_service.dart';
// 组件
import 'package:chat_client/widgets/c_loading.dart';
//工具
import 'package:chat_client/utils/validation.dart';
import 'package:chat_client/utils/image-picker/image_picker_helper.dart';
import 'package:chat_client/utils/show_messae.dart';

class LoginProvider extends ChangeNotifier {
  // 服务
  final LoginService _loginService = LoginService.instance;

  // 文本控制器
  final TextEditingController usernameController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  final TextEditingController nicknameController = TextEditingController();
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController captchaController = TextEditingController();
  XFile? _selectedImage; // 文件对象
  // 验证码唯一标识
  String? _captchaUid;

  /// 获取当前头像路径（安全访问）
  XFile? get imageXFile => _selectedImage;

  @override
  void dispose() {
    usernameController.dispose();
    passwordController.dispose();
    nicknameController.dispose();
    phoneController.dispose();
    captchaController.dispose();
    // 释放图片资源
    ImagePickerHelper.releaseImage(_selectedImage);
    super.dispose();
  }

  // 设置验证码标识
  void handleCaptchaUidChanged(String? uid) {
    _captchaUid = uid;
  }

  /// 选择图片
  Future<void> pickImage() async {
    try {
      final file = await ImagePickerHelper.pickAndProcessImage();
      if (file == null) return;
      _selectedImage = file;
      notifyListeners(); //通知更新UI
    } catch (e) {
      print('图片处理失败${e.toString()}');
    }
  }

  // 登录逻辑
  Future<void> login() async {
    try {
      Loading.show(message: "登录中...");

      final username = usernameController.text.trim();
      final password = passwordController.text.trim();

      // 登录校验
      String? errorText = validateLogin(
        username: username,
        password: password,
      );

      if (errorText != null) {
        popError(errorText, '登录失败');
        Loading.hide();
        return;
      }

      await _loginService.login(username, password);
      _navToHome();
    } catch (e) {
      popError(e.toString(), '登录失败');
    } finally {
      Loading.hide();
    }
  }

  /// 注册逻辑
  Future<void> register() async {
    try {
      Loading.show(message: "正在注册...");

      final phoneNumber = phoneController.text.trim();
      final password = passwordController.text.trim();
      final captcha = captchaController.text.trim();
      final nickname = nicknameController.text.trim();

      // 注册校验
      String? errorText = validateRegister(
          nickname: nickname,
          phoneNumber: phoneNumber,
          password: password,
          authCode: captcha);

      if (errorText != null) {
        popError(errorText, '注册失败');
        Loading.hide();
        return;
      }

      await _loginService.register(
        password: password,
        phoneNumber: phoneNumber,
        captchaCode: captcha,
        captchaUid: _captchaUid!,
        // mobile端专属
        nickname: nickname,
        imageFile: _selectedImage,
      );

      _navToHome();
    } catch (e) {
      popError(e.toString(), '注册失败');
    } finally {
      Loading.hide();
    }
  }

  /// 路由转跳
  // 替换栈顶路由
  _navToHome() {
    if (kIsWeb) {
      RouteManager.replaceWith('/mobile-home');
      // RouteManager.navigateTo('/web-home');
    } else {
      RouteManager.replaceWith('/mobile-home');
    }
  }

  // mobile register
  navToRegister() {
    RouteManager.navigateTo('/mobile-register');
  }

  // 手动清理password
  clearPassword() {
    passwordController.clear();
  }
}
